<template>
  <!-- 问卷新增编辑页 -->
  <div class="questionnaire question-content-wrap" :loading="loading">
    <div class="questionnaire-container">
      <el-scrollbar style="height:calc(100vh - 120px)" wrap-class="scrollbar-wrapper">
        <div class="ques-header">
          <h1>问卷编辑器</h1>
          <div class="ques-header-btns">
            <Button type="primary" @click="addType=3;$refs.editItem.openDailog()">添加章节</Button>
            <!-- <Button type="primary" @click="addType=0;$refs.editItem.openDailog()">添加题目</Button> -->
            <QuesRemarks
              text="备注"
              title="备注"
              style="margin-left: 10px"
              :value="formData.remark"
              @confrimFunc="(remark)=>{formData.remark=remark;updateBase()}"
            ></QuesRemarks>
            <Button type="primary" @click="preview">预览</Button>
            <Button type="primary" @click="release">发布</Button>
          </div>
        </div>
        <div class="ques-cont">
          <FormContainer :column="1">
            <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
              <el-form-item prop="title" label="标题:">
                <el-input
                  v-model.trim="formData.title"
                  tip
                  :maxlength="100"
                  @blur="updateBase('', 'form', 'title')"
                ></el-input>
              </el-form-item>
              <el-form-item v-if="formData.questionnaireSort===0" prop="startWords" label="开头语:">
                <el-input
                  v-model.trim="formData.startWords"
                  :autosize="{minRows: 4}"
                  placeholder="请输入问卷开头语"
                  tip
                  :maxlength="1000"
                  type="textarea"
                  @blur="updateBase('', 'form', 'startWords')"
                ></el-input>
              </el-form-item>
              <el-form-item label="题目:">
                <div v-if="formData.questionnaireChapterDTOList.length" class="ques-subject-area">
                  <!-- 章节 -->
                  <div
                    v-for="(chaper,index) in formData.questionnaireChapterDTOList"
                    :key="index"
                    class="chapter"
                  >
                    <div
                      style="position:relative;padding:17px 0"
                      @mouseenter="chaper.show=true"
                      @mouseleave="chaper.show=false"
                    >
                      <p
                        style="font-size:1.2rem;margin:0;font-weight:600"
                      >{{ chaper.chapter_index_text+'、'+ chaper.chapterTitle }}</p>
                      <Controls
                        :item="JSON.parse(JSON.stringify(chaper))"
                        :show="chaper.show"
                        :questionnaire-id="formData.id"
                        :is-score="formData.questionnaireSort"
                        :list="formData.questionnaireChapterDTOList"
                        @refresh="refresh"
                      ></Controls>
                    </div>

                    <Item
                      v-for="(item,index1) in chaper.questionnaireQuestionDTOList"
                      :key="index1"
                      :item="item"
                      :answer="answer"
                      :chaper-id="chaper.id"
                      :list="chaper.questionnaireQuestionDTOList"
                      type="0"
                      @refresh="refresh"
                    ></Item>
                    <Controls
                      :item="JSON.parse(JSON.stringify(chaper))"
                      :questionnaire-id="formData.id"
                      :is-score="formData.questionnaireSort"
                      :list="formData.questionnaireChapterDTOList"
                      edit-item
                      show
                      style="position:static !important;"
                      @refresh="refresh"
                    ></Controls>
                  </div>
                </div>
              </el-form-item>
              <el-form-item v-if="formData.questionnaireSort===0" prop="endWords" label="结束语:">
                <el-input
                  v-model.trim="formData.endWords"
                  placeholder="请输入问卷结束语"
                  :autosize="{minRows:4}"
                  type="textarea"
                  tip
                  :maxlength="1000"
                  @blur="updateBase('', 'form', 'endWords')"
                ></el-input>
              </el-form-item>
            </el-form>
          </FormContainer>
        </div>
      </el-scrollbar>
    </div>
    <el-dialog
      :visible.sync="add"
      title="新建问卷"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="resetFormData"
    >
      <el-alert
        title="问卷新增和编辑界面有自动保存功能，无需手动保存"
        type="info"
        :closable="false"
        style="margin:-10px 0 10px 0"
      >
      </el-alert>
      <FormContainer :column="1">
        <el-form ref="addform" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item prop="title" label="问卷名称">
            <el-input v-model="formData.title" :maxlength="100" tip placeholder="请输入问卷名称" />
          </el-form-item>
          <!-- <el-form-item prop="questionnaireSort" label="问卷用途">
            <el-radio-group v-model="formData.questionnaireSort">
              <el-radio :label="0">回访问卷</el-radio>
              <el-radio :label="1">质检问卷</el-radio>
            </el-radio-group>
          </el-form-item> -->
        </el-form>
      </FormContainer>
      <span slot="footer" class="dialog-footer">
        <Button @click="returnPage">取消</Button>
        <Button type="primary" :loading="loading" @click="addQuestionnaire">确定</Button>
      </span>
    </el-dialog>
    <EditItem
      ref="editItem"
      :type="addType"
      :index-num="formData.questionnaireChapterDTOList.length"
      :questionnaire-id="formData.id"
      :is-score="formData.questionnaireSort"
      @confrimFunc="addItem"
    />
    <!-- 查看预览 -->
    <Preview ref="questionnairePreview"></Preview>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import QuesRemarks from './components/QuesRemarks'
import EditItem from './components/EditItem'
import Item from './components/Item'
import Preview from './components/Preview'
import Controls from './components/Controls'
import { questionnaireDataSet } from '@/utils/questionnaire'
import {
  questionnaireAddGetId,
  questionnaireDetailById,
  questionnaireUpdate
} from '@/api/questionnaire'
export default {
  name: 'QuestionnaireAddEdit',
  components: {
    FormContainer,
    Button,
    QuesRemarks,
    EditItem,
    Item,
    Preview,
    Controls
  },
  data() {
    return {
      add: false,
      contorlShow: false,
      titleEdit: false,
      startWordEdit: false,
      endWordEdit: false,
      loading: false,
      dialogVisible: false,
      addType: 3,
      answer: {},
      formData: {
        endWords: '', // 结束语
        questionnaireSort: '', // 问卷用途：0回访问卷1质检问卷
        remark: '', // 问卷备注或说明
        startWords: '', // 开场白
        state: 0, // 问卷状态：0未发布1已发布
        title: '', // 问卷标题
        id: '1',
        questionnaireChapterDTOList: []
      },
      formRules: {
        title: [{
          required: true,
          message: '请输入问卷名称',
          trigger: 'change'
        }],
        questionnaireSort: [{
          required: true,
          message: '请选择问卷用途',
          trigger: 'change'
        }]
      }
    }
  },
  activated() {
    const questionnaireId = window.sessionStorage.questionnaireId
    if (this.$route.query.type || this.$route.query.type === 0 || this.$route.query.type === '0') {
      this.formData.questionnaireSort = this.$route.query.type
    } else {
      // this.returnPage()
    }
    if (questionnaireId) {
      this.refresh(questionnaireId)
      this.formData.id = questionnaireId
    } else {
      this.formData.id = ''
      this.add = !this.formData.id
    }
  },
  methods: {
    // 预览
    preview() {
      this.$refs.questionnairePreview.openDailog(this.formData)
    },
    // 添加章节或题目
    addItem() {
      this.refresh()
    },
    // 关闭问卷重置表单
    resetFormData() {
      this.$refs.addform.resetFields()
    },
    // 新建问卷
    addQuestionnaire() {
      this.$refs.addform.validate(valid => {
        if (valid) {
          this.loading = true
          questionnaireAddGetId(this.formData)
            .then(res => {
              if (res.code === '') {
                this.formData.id = res.msg
                this.add = false
                window.sessionStorage.questionnaireId = res.msg
              }
              this.$refs.addform.resetFields()
              this.refresh(res.msg)
              this.loading = false
            })
            .catch(er => {
              this.loading = false
            })
        }
      })
    },
    // 更新问卷基础信息
    updateBase(type, form, field) {
      let p = Promise.resolve()
      if (form && field) {
        this.$refs[form].validateField(field, errMsg => {
          if (errMsg) {
            p = Promise.reject(errMsg)
          } else {
            p = Promise.resolve()
          }
        })
      }
      if (form && !field) {
        p = this.$refs[form].validate()
      }
      p.then(() => {
        var reqData = {
          endWords: this.formData.endWords,
          id: this.formData.id,
          questionnaireSort: this.formData.questionnaireSort,
          remark: this.formData.remark,
          startWords: this.formData.startWords,
          state: this.formData.state,
          title: this.formData.title
        }
        questionnaireUpdate(reqData).then(res => {
          reqData = {}
          this.titleEdit = false
          this.startWordEdit = false
          this.endWordEdit = false
          if (type) {
            this.returnPage()
          }
        })
      })
    },
    // 刷新问卷
    refresh(id, type) {
      this.loading = true
      questionnaireDetailById(id || this.formData.id).then(res => {
        if (res.success === 1) {
          const obj = questionnaireDataSet(
            res.data,
            res.data.questionnaireChapterDTOList
          )
          this.loading = false
          this.formData = obj.questionnaire
          this.answer = obj.answer
          this.$forceUpdate()
        }
      })
    },
    // 发布
    release() {
      this.$confirm('是否确认发布?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.formData.state = 1
          this.updateBase(1)
        })
        .catch(() => {})
    },
    // 新增问卷时取消
    returnPage() {
      this.formData.id = '1'
      this.add = false
      this.$closePage()
    }
  }
}
</script>
<style lang='scss' scoped>
.questionnaire-container {
  background: #ffffff;
  border-radius: 4px;
  position: relative;
  .ques-header {
    position: absolute;
    background: #ffffff;
    top: 0;
    left: 0;
    width: 100%;
    height: 70px;
    z-index: 1;
    h1 {
      margin: 0;
      text-align: center;
      line-height: 70px;
    }
    .ques-header-btns {
      position: absolute;
      top: 0;
      right: 0;
      display: flex;
      align-items: center;
      height: 100%;
      > * {
        margin-right: 10px;
      }
    }
  }
  .ques-cont {
    padding: 70px 10px 20px;
    overflow-y: auto;
    .ques-title {
      height: 60px;
      display: flex;
      align-items: center;
      > span {
        background: #fff;
        display: inline-block;
        padding: 5px 0;
        display: inline-block;
        width: 50%;
        text-align: center;
        font-size: 1.2rem;
        letter-spacing: 2px;
        border-radius: 2px;
      }
    }
    .startWords_area {
      position: relative;
      .startWords_content {
        padding: 0 10px;
        height: 100px;
        border-radius: 2px;
        background: #fff;
        p {
          margin: 0;
          font-size: 14px;
          line-height: 28px;
        }
      }
    }
    .startWords_area {
      margin-top: 18px;
    }
    .ques-subject-area {
      border:1px solid #DCDFE6;
      border-radius: 4px;
      background: #ffffff;
      padding: 10px;
    }
  }
}
.chapter {
  position: relative;
}
.el-form-item__label{
  font-size: 1.2rem;
  font-weight: bold;
}
</style>
<style lang="scss">
  .question-content-wrap{
    & [class*="el-checkbox__label"]{
      display: inline-block;
      max-width: 100%;
      word-wrap: break-word;
      white-space: break-spaces;
      word-break: break-all;
      vertical-align: text-top;
    }
  }
</style>
